package com.heima.homeservicemanagementsystem.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.homeservicemanagementsystem.entity.ServiceClassification;
import com.heima.homeservicemanagementsystem.entity.Servicedetails;
import com.heima.homeservicemanagementsystem.entity.vo.ServiceAndDetailVo;
import com.heima.homeservicemanagementsystem.mapper.ServiceClassificationMapper;
import com.heima.homeservicemanagementsystem.mapper.ServiceServicedetailMapper;
import com.heima.homeservicemanagementsystem.service.ServiceClassificationService;
import com.heima.homeservicemanagementsystem.service.ServicedetailsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.heima.homeservicemanagementsystem.module.PageParams;
import com.heima.homeservicemanagementsystem.module.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.heima.homeservicemanagementsystem.entity.ServiceServicedetail;
import com.heima.homeservicemanagementsystem.service.ServiceServicedetailService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.dev33.satoken.SaManager.log;

/**
 * 服务和服务详情;(service_servicedetail)表控制层
 *
 * @author : http://www.chiner.pro
 * @date : 2025-4-15
 */
@Slf4j
@Tag(name = "服务和服务详情对象功能接口")
@RestController
@RequestMapping("/serviceServicedetail")
public class ServiceServicedetailController {

    @Resource
    private ServiceServicedetailService serviceServicedetailService;
    @Resource
    private ServiceClassificationService serviceClassificationService;
    @Resource
    private ServiceClassificationMapper serviceClassificationMapper;
    @Resource
    private ServicedetailsService servicedetailsService;
    @Autowired
    private ServiceServicedetailMapper serviceServicedetailMapper;

    @SaIgnore
    @Operation(summary = "分页查询")
    @PostMapping("/page")
    public Result<Page<Servicedetails>> paginQuery(@RequestBody PageParams<ServiceServicedetail> pageParams) {
        //查询参数
        ServiceServicedetail params = pageParams.getParams();
        LambdaQueryWrapper<ServiceServicedetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(params != null && params.getId() != null, ServiceServicedetail::getServiceid, params.getId());
        List<ServiceServicedetail> list = serviceServicedetailService.list(lqw);


        Page<ServiceServicedetail> page = serviceServicedetailService.page(pageParams.getPage(), lqw);
        List<ServiceServicedetail> records = page.getRecords();
        ArrayList<Servicedetails> objects = new ArrayList<>();
        Page<Servicedetails> objectPageParams = new Page<>();
        for (ServiceServicedetail record : records) {

            Servicedetails byId = servicedetailsService.getById(record.getDetailid());
            objects.add(byId);


        }
        objectPageParams.setRecords(objects);
        objectPageParams.setTotal(page.getTotal());
        objectPageParams.setPages(page.getPages());
        objectPageParams.setCurrent(page.getCurrent());

        return Result.success(objectPageParams);


    }

    /**
     * 即可达的相关
     *
     * @return com.heima.homeservicemanagementsystem.module.Result
     * @author jinchengfei
     * @create 2025/4/15
     **/
    @SaIgnore
    @Operation(summary = "即可达")
    @GetMapping("/getReachableImmediately")
    public Result getReachableImmediately() {

        List<ServiceClassification> serviceClassifications = serviceClassificationMapper.selectList(
                new LambdaQueryWrapper<ServiceClassification>().eq(ServiceClassification::getType, 1)
                        .last("ORDER BY RAND() LIMIT 5")

        );
        log.info("总数：{}", serviceClassifications);


        return Result.success(serviceClassifications);
    }

    /**
     * 根据id查询全部详细信息
     **/
    @Operation(summary = " 根据id查询关联详细信息", parameters = {@Parameter(name = "Id", description = "主键", required = true, in = ParameterIn.PATH)})
    @GetMapping("/getserviceInfoByid/{Id}")
    public Result getserviceInfoByid(@PathVariable String Id) {
//
        QueryWrapper<ServiceServicedetail> wrapper = new QueryWrapper<>();
        wrapper.eq("serviceId", Id);
        List<ServiceServicedetail> list = serviceServicedetailService.list(wrapper);
        log.info("xinxi：{}", list);
        ArrayList<Servicedetails> objects = new ArrayList<>();
        list.stream().forEach(item -> {
            Servicedetails byId = servicedetailsService.getById(item.getDetailid());
            objects.add(byId);
        });
        return Result.success(objects);
    }

    @Operation(summary = "分类下的服务数量")
    @GetMapping("/Servicelist")
    public Result searchQuery2() {
        // 创建查询条件，查询所有记录
        LambdaQueryWrapper<ServiceServicedetail> queryWrapper = new LambdaQueryWrapper<>();

        // 按照 serviceid 字段进行分组，并统计每个 serviceid 出现的次数


        // 执行查询并获取统计结果
        List<Map<String, Object>> resultList = serviceServicedetailMapper.selectServiceidCount(queryWrapper);
        log.info("统计结果：{}", resultList);

        // 创建一个 map 用于存储最终的分类名称和对应的数量
        List<Map<String, Object>> result = new ArrayList<>();

        // 遍历查询结果，逐个获取分类名称及其对应的数量
        for (Map<String, Object> row : resultList) {
            // 从查询结果中获取 serviceid 和其对应的数量
            String serviceid = row.get("serviceid").toString();
            Long count = (Long) row.get("serviceid_count");
            log.info("serviceid: {}, count: {}", serviceid, count);
            // 根据 serviceid 获取对应的 ServiceClassification 对象
            ServiceClassification detailid = serviceClassificationService.getById(serviceid);
            String flName = detailid.getFlName();

            Map<String, Object> map = new HashMap<>();
            map.put("name", flName);  // 这里 flName 对应的就是你的 name 字段
            map.put("total", count);   // 这里 count 对应的就是你的 count 字段

            // 将 map 添加到结果列表中
            result.add(map);


        }

        // 返回结果
        return Result.success(result);
    }

    @Operation(summary = "服务和服务详情所有搜索")
    @GetMapping("/list")

    public Result searchQuery() {
        // 获取服务和服务详情列表
        List<ServiceServicedetail> list = serviceServicedetailService.list();

        // 创建一个集合来存储每个查询项的结果
        List<ServiceAndDetailVo> resultList = getServiceAndDetailVos(list);

        // 返回包含所有查询结果的列表
        return Result.success(resultList);
    }

    @Operation(summary = "有条件的搜索")
    @PostMapping("/tjSearch")
    public Result Query(@RequestBody ServiceServicedetail serviceServicedetail) {
        log.info("前端信息：{}", serviceServicedetail);
        LambdaQueryWrapper<ServiceServicedetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(serviceServicedetail.getId() != null, ServiceServicedetail::getId, serviceServicedetail.getId());
        lqw.eq(serviceServicedetail.getServiceid() != null, ServiceServicedetail::getServiceid, serviceServicedetail.getServiceid());
        lqw.eq(serviceServicedetail.getDetailid() != null, ServiceServicedetail::getDetailid, serviceServicedetail.getDetailid());
        List<ServiceServicedetail> list = serviceServicedetailService.list(lqw);
        List<ServiceAndDetailVo> resultList = getServiceAndDetailVos(list);
        return Result.success(resultList);
    }

    private List<ServiceAndDetailVo> getServiceAndDetailVos(List<ServiceServicedetail> list) {
        // 创建一个集合来存储每个查询项的结果
        List<ServiceAndDetailVo> resultList = new ArrayList<>();

        // 遍历每个 ServiceServicedetail，查询对应的 ServiceClassification 和 Servicedetails
        list.stream().forEach(item -> {

            String serviceid = item.getServiceid();
            String detailid = item.getDetailid();

            // 查询 ServiceClassification 和 Servicedetails
            ServiceClassification byId = serviceClassificationService.getById(serviceid);
            Servicedetails byId1 = servicedetailsService.getById(detailid);

//            // 创建 JSONObject 用于存储每个查询项的结果
//            JSONObject entries = new JSONObject();
//            entries.putOnce("service", byId); // 将 ServiceClassification 放入 JSONObject
//            entries.putOnce("detailid", byId1); // 将 Servicedetails 放入 JSONObject
            ServiceAndDetailVo serviceAndDetailVo = new ServiceAndDetailVo();
            serviceAndDetailVo.setService(byId);
            serviceAndDetailVo.setDetailid(byId1);
            serviceAndDetailVo.setId(item.getId());
            // 将 JSONObject 添加到结果列表
            resultList.add(serviceAndDetailVo);
        });
        return resultList;
    }

    /**
     * 新增数据
     *
     * @param serviceServicedetail 实例对象
     * @return 实例对象
     */
    @Operation(summary = "新增数据")
    @PostMapping("/insert")
    public Result<Boolean> insert(@RequestBody ServiceServicedetail serviceServicedetail) {
        QueryWrapper<ServiceServicedetail> wrapper = new QueryWrapper<>();
        wrapper.eq("serviceId", serviceServicedetail.getServiceid());
        wrapper.eq("detailId", serviceServicedetail.getDetailid());
        boolean exists = serviceServicedetailService.exists(wrapper);
        if (exists) {
            return Result.error("该服务和服务详情已存在");
        }
        if (serviceServicedetailService.save(serviceServicedetail)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 更新数据
     *
     * @param serviceServicedetail 实例对象
     * @return 实例对象
     */
    @Operation(summary = "更新数据")
    @PutMapping("update")
    public Result<Boolean> update(@RequestBody ServiceServicedetail serviceServicedetail) {
        if (serviceServicedetailService.updateById(serviceServicedetail)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 通过主键删除数据
     *
     * @param undefinedId 主键
     * @return 是否成功
     */
    @Operation(summary = "通过主键删除数据",
            parameters = {
                    @Parameter(name = "undefinedId", description = "主键", required = true, in = ParameterIn.PATH)
            })
    @DeleteMapping("/delete/{undefinedId}")
    public Result<Boolean> deleteById(@PathVariable String undefinedId) {

        if (serviceServicedetailService.removeById(undefinedId)) {
            return Result.success();
        }
        return Result.error();
    }

    @Operation(summary = "多id删除数据")
    @DeleteMapping("/delete")
    public Result<Boolean> deleteByIds(@RequestBody List<String> id) {
        log.info("前端信息：{}", id);
        if (serviceServicedetailService.removeByIds(id)) {
            return Result.success();
        }
        return Result.error();
    }
}